package gui.sql;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DBQuery {
	private int blockSize = 100;
	private int lastId;

	public DBQuery() {
	}

	public DBQuery(int blockSize, int lastId) {
		super();
		this.blockSize = blockSize;
		this.lastId = lastId;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public void setLastId(int lastId) {
		this.lastId = lastId;
	}

	public <T> void search(int iwant, Class<T> table, DBQueryCallback<T> cb, String[] column, String keyWord,
			boolean isWeak) {
		String[] split = keyWord.split("[ ]");
		StringBuffer sb = new StringBuffer();
		List<Object> paramsList = new ArrayList<>();
		for (int i = 0; i < column.length; i++) {
			String c = column[i];
			sb.append("(");
			for (int j = 0; j < split.length; j++) {
				String key = split[j];
				sb.append(c).append(" like ").append("?");
				paramsList.add("%" + key + "%");
				if (j != split.length - 1) {
					sb.append(isWeak ? " or " : " and ");
				}
			}
			sb.append(")");
			if (i != column.length - 1) {
				sb.append(" or ");
			}
		}
		Object[] params = new Object[paramsList.size()];
		for (int i = 0; i < params.length; i++) {
			params[i] = paramsList.get(i);
		}
		query(iwant, table, cb, sb.toString(), params);
	}

	/**
	 * @param iwant
	 * @param table
	 * @param cb
	 * @param queryCondition
	 *            只输入条件部分
	 * @param params
	 */
	public <T> void query(int iwant, Class<T> table, DBQueryCallback<T> cb, String queryCondition, Object... params) {
		int blockCount = 0;
		int last = DBHelper
				.queryEntityList(Id.class,
						"select id from " + table.getSimpleName().toLowerCase() + " order by id desc limit ?,?", 1, 1)
				.get(0).getId();
		String sql = "select * from " + table.getSimpleName().toLowerCase() + " where (" + queryCondition
				+ ")and id>=? and id<?";
		Object[] copyOf = Arrays.copyOf(params, params.length + 2);
		List<T> list;
		int start, end;
		do {
			start = lastId + (blockSize * blockCount++);
			end = start + getBlockSize();
			if (start > last) {
				break;
			}
			copyOf[params.length] = start;
			copyOf[params.length + 1] = end;
			list = DBHelper.queryEntityList(table, sql, copyOf);
			if (list != null && (list.size() - iwant) > 0) {
				for (int i = list.size() - 1; i >= iwant; i--) {
					list.remove(i);
				}
			}
		} while ((iwant = cb.nextBlock(list)) > 0);
		cb.stop();
	}

	public static interface DBQueryCallback<E> {
		/**
		 * 
		 * @param result
		 *            本次插叙结果
		 * @return 还剩几条数据
		 */
		int nextBlock(List<E> result);

		/**
		 * 结束时回调方法
		 */
		void stop();
	}
}
